(function () {

  'use strict';

  angular
  .module('app')
  .controller('InfoController', InfoController);

  InfoController.$inject = ['$scope', '$http', '$window', '$timeout', '$location', '$state', '$stateParams', 'API', 'ENUM', 'AppAuthenticationService', 'ConfirmProductService', 'CartModel','ConfigModel', '$rootScope'];

  function InfoController($scope, $http, $window, $timeout, $location, $state, $stateParams, API, ENUM, AppAuthenticationService, ConfirmProductService, CartModel, ConfigModel, $rootScope) {

      var MAX_COMMENTS = 3;
      var goodsID = $stateParams.goods_id;

      $scope.input = {
          currentAmount: 1
      };

      $scope.goods = null;
      $scope.canPurchase = true;
      $scope.comments = [];
      $scope.isLoading = false;
      $scope.isLoaded = false;
      $scope.cartModel = CartModel;

      $scope.touchAmountSub = function() {
          if (!$scope.goods) return;

          var amount = parseInt($scope.input.currentAmount);
          if ( amount <= 1 ) {
              $scope.toast('受不了了，宝贝不能再少了');
              return;
          }

          $scope.input.currentAmount = (amount - 1);
      };

      $scope.touchAmountAdd = function() {
          if (!$scope.goods) return;
          var amount = parseInt($scope.input.currentAmount);
          $scope.input.currentAmount =  (amount + 1);
      };

      $scope.touchComment = function () {
          $state.go('comment', {
              goods_id: goodsID
          });
      };

      $scope.touchCart = function() {
          if ( !AppAuthenticationService.getToken() ) {
              $scope.goSignin();
              return;
          }
          $state.go('cart', {});
      };

      $scope.touchAddCart = function() {
          if ( !AppAuthenticationService.getToken() ) {
              $scope.goSignin();
              return;
          }

          var num = Number($scope.input.currentAmount);
          CartModel.add(goodsID, num).then(function(succeed){
              if ( succeed ) {
                  $scope.toast('已添加到购物车');
              }
          });
      };

      $scope.touchPurchase = function () {
          if ( !AppAuthenticationService.getToken() ) {
              $scope.goSignin();
              return;
          }

          var amount = Number($scope.input.currentAmount);

          ConfirmProductService.clear();
          ConfirmProductService.goods = $scope.goods;
          ConfirmProductService.amount = amount;

          $state.go('confirm-product', {});
      };

      $scope.refreshAmount = function(){
          var amount = parseInt($scope.input.currentAmount);
          if (amount < 1) {
              $scope.input.currentAmount = 1;
          }
      };

      function _reload() {
          $scope.isLoading = true;

          API.goods.getOne({goods_id:goodsID}).then(function(res){
              $scope.goods = res;
              $scope.isLoaded = true;
              $scope.isLoading = false;
              var config = ConfigModel.getConfig();
              if (config) {
                  var wechat = config['wxpay.web'];
                  if(wechat){
                      _initConfig(wechat,$scope.goods);
                  }
              } else {
                  ConfigModel.fetch().then(function(){
                      var config = ConfigModel.getConfig();
                      if(config){
                          var wechat = config['wxpay.web'];
                          if(wechat){
                              _initConfig(wechat,$scope.goods);
                          }
                      }
                  });
              }
              _reloadComments();
          });
      }

      function _initConfig(wechat,goods){

                if ( !wechat ) {
                    return;
                };
                var url = goods.share_url?goods.share_url:GLOBAL_CONFIG.WX_HOST+'#/goods-info?goods_id='+goods.goods_id;
                wx.config({
                    debug: GLOBAL_CONFIG.DEBUG, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: wechat.appId, // 必填，公众号的唯一标识
                    timestamp: wechat.timestamp, // 必填，生成签名的时间戳
                    nonceStr: wechat.nonceStr, // 必填，生成签名的随机串
                    signature: wechat.signature,// 必填，签名，见附录1
                    jsApiList: ['chooseWXPay',
                        'onMenuShareAppMessage',
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });

                wx.ready( function() {
                    wx.onMenuShareTimeline({
                        title: '商品详情', // 分享标题
                        desc:goods.goods_name,
                        link: url, // 分享链接
                        imgUrl: goods.cover_img, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });

                    wx.onMenuShareAppMessage({
                        title: '商品详情', // 分享标题
                        desc:goods.goods_name,
                        link: url, // 分享链接
                        imgUrl: goods.cover_img, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });

                    wx.onMenuShareQQ({
                        title: '商品详情', // 分享标题
                        desc:goods.goods_name,
                        link: url, // 分享链接
                        imgUrl: goods.cover_img, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.onMenuShareWeibo({
                          title: '商品详情', // 分享标题
                        desc:goods.goods_name,
                        link: url, // 分享链接
                        imgUrl: goods.cover_img, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });

                });

                wx.error(function(res){
                    if(GLOBAL_CONFIG.DEBUG){
                        $rootScope.toast(JSON.stringify(res));
                    }
                });

      }

      function _reloadComments() {
          if ( !$scope.goods )
              return;

          API.review.goodsComment({
              relation_id :goodsID,
              level: ENUM.REVIEW_GRADE.ALL,
              type: 1,
              page: 1,
              per_page: MAX_COMMENTS
          }).then(function(comments){
              $scope.comments = comments;
          });
      }

      _reload();
  }

})();
